from LCD1602 import print_lcd, init_lcd, clear_lcd, scan_lcd
import time
import requests

location = ["GD Chaozhou", "BJ Beijing"]
cityname = ["chaozhou",    "beijing"   ]

def print_weather(cid):
    req = requests.get("https://api.seniverse.com/v3/weather/now.json?key={key}&location="+cityname[cid]+"&language=en&unit=c") # 这里可以去申请一下这个免费接口，其他的接口也可以
    if req.json()["status_code"] == "AP010003":
        raise Exception("Please take the right key.")
    data = req.json()["results"][0]["now"]
    temperature = data["temperature"]
    weather = data["text"]
    clear_lcd()
    print_lcd(0, 0, location[cid])
    print_lcd(0, 1, weather+' '+temperature+chr(0xDF)+'C')

if __name__ == "__main__":
    init_lcd()
    count = 0
    cid = 0
    print_weather(cid)
    while True:
        if count == 600:
            count = 0
            print_weather(cid)
        time.sleep(0.1)
        op = scan_lcd()
        if op == 4:
            cid = cid-1 if cid>0 else 0
            print_weather(cid)
        if op == 1:
            cid = cid+1 if cid<1 else 1
            print_weather(cid)
        count += 1